package com.wenya.counter.ui.main;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;

import com.wenya.counter.data.bean.ScriptureBean;
import com.wenya.counter.data.db.CounterDatabase;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MainViewModel extends AndroidViewModel implements DefaultLifecycleObserver {
    public MutableLiveData<List<ScriptureBean>> dataList = new MutableLiveData<>();
    public MediatorLiveData<Integer> houseNumber = new MediatorLiveData<>();

    public MainViewModel(@NonNull Application application) {
        super(application);
        houseNumber.addSource(dataList, this::cutHoseNumber);
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        loadData();
    }

    public void loadData() {
        dataList.setValue(CounterDatabase.getInstance().basicDataDao().getAll());
    }

    public void cutHoseNumber(List<ScriptureBean> scriptureBeans) {
        if (scriptureBeans == null || scriptureBeans.size() == 0) {
            houseNumber.setValue(0);
        } else {
            int total = Integer.MAX_VALUE;
            for (ScriptureBean scriptureBean : scriptureBeans) {
                total = Math.min(total, scriptureBean.getTimes() / scriptureBean.getDivisor());
            }
            houseNumber.setValue(total);
        }
    }

    public void resetData() {
        List<String> keys = getNames();
        if (keys == null) return;
        CounterDatabase.getInstance().basicDataDao().reset(keys);
    }

    @Nullable
    private List<String> getNames() {
        List<ScriptureBean> list = dataList.getValue();
        if (list == null || list.size() == 0) {
            return null;
        }
        List<String> keys = new ArrayList<>();
        for (ScriptureBean item : list) {
            if (item.isChecked()) {
                keys.add(item.getName());
            }
        }
        return keys;
    }

    public void delete() {
        List<String> keys = getNames();
        if (keys == null) return;
        CounterDatabase.getInstance().basicDataDao().delete(keys);
    }
}